const app = getApp()

Page({
  data: {
    tabs: ['进行中', '已成团', '已失败'],
    currentTab: 0,
    groupBuys: [],
    statusBarHeight: 0,
    navbarHeight: 0
  },

  onLoad() {
    // 获取系统信息，用于适配状态栏高度
    const systemInfo = wx.getSystemInfoSync()
    const statusBarHeight = systemInfo.statusBarHeight || 0
    // 导航栏总高度 = 状态栏高度 + 88rpx (导航栏内容高度，约44px)
    const navbarHeight = statusBarHeight + 44
    this.setData({
      statusBarHeight: statusBarHeight,
      navbarHeight: navbarHeight
    })
    this.loadGroupBuys()
  },

  onShow() {
    this.loadGroupBuys()
  },

  loadGroupBuys() {
    const groupBuys = wx.getStorageSync('groupBuys') || this.getMockGroupBuys()
    const filteredGroupBuys = this.filterGroupBuys(groupBuys, this.data.currentTab)
    
    this.setData({
      groupBuys: filteredGroupBuys
    })
  },

  getMockGroupBuys() {
    return [
      {
        id: 1,
        productId: 3,
        productTitle: '北京故宫紫禁城门票',
        productImage: '',
        originalPrice: 1200,
        groupPrice: 999,
        currentCount: 3,
        targetCount: 5,
        endTime: new Date(Date.now() + 12 * 60 * 60 * 1000).toISOString(), // 12小时后
        status: 'ongoing',
        groupId: 'GB001',
        members: [
          { avatar: '', nickname: '用户1' },
          { avatar: '', nickname: '用户2' },
          { avatar: '', nickname: '用户3' }
        ]
      },
      {
        id: 2,
        productId: 2,
        productTitle: '水舞间水上汇演门票',
        productImage: '',
        originalPrice: 367,
        groupPrice: 300,
        currentCount: 5,
        targetCount: 5,
        endTime: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString(),
        status: 'success',
        groupId: 'GB002',
        successTime: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString()
      },
      {
        id: 3,
        productId: 1,
        productTitle: '毕业趣旅行-高星好评-四日解锁京城',
        productImage: '',
        originalPrice: 400,
        groupPrice: 350,
        currentCount: 2,
        targetCount: 5,
        endTime: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000).toISOString(),
        status: 'failed',
        groupId: 'GB003'
      }
    ]
  },

  filterGroupBuys(groupBuys, tabIndex) {
    const statusMap = ['ongoing', 'success', 'failed']
    const status = statusMap[tabIndex]
    
    return groupBuys.filter(item => item.status === status).map(item => {
      const endTime = new Date(item.endTime)
      const now = new Date()
      const diff = endTime - now
      
      let timeText = ''
      if (item.status === 'ongoing') {
        if (diff > 0) {
          const hours = Math.floor(diff / (1000 * 60 * 60))
          const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
          timeText = hours > 0 ? `${hours}小时${minutes}分钟` : `${minutes}分钟`
        } else {
          timeText = '已过期'
        }
      } else if (item.status === 'success') {
        timeText = this.formatTime(item.successTime)
      } else {
        timeText = this.formatTime(item.endTime)
      }
      
      return {
        ...item,
        timeText,
        formattedGroupPrice: item.groupPrice.toFixed(2),
        formattedOriginalPrice: item.originalPrice.toFixed(2),
        progress: Math.round((item.currentCount / item.targetCount) * 100),
        needCount: item.targetCount - item.currentCount
      }
    })
  },

  formatTime(timeStr) {
    const date = new Date(timeStr)
    const month = date.getMonth() + 1
    const day = date.getDate()
    return `${month}月${day}日`
  },

  switchTab(e) {
    const index = e.currentTarget.dataset.index
    this.setData({
      currentTab: index
    })
    this.loadGroupBuys()
  },

  goToProductDetail(e) {
    const productId = e.currentTarget.dataset.productId
    wx.navigateTo({
      url: `/pages/product-detail/product-detail?id=${productId}`
    })
  },

  goToGroupDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/group-buy-detail/group-buy-detail?id=${id}`
    })
  },

  shareGroup(e) {
    const id = e.currentTarget.dataset.id
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
    
    wx.showToast({
      title: '分享给好友参团',
      icon: 'none'
    })
  },

  goBack() {
    wx.navigateBack()
  }
})

